package sale.wxb.loveshopping.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 数据查询分页
 */
public class DataPageUtilBuild <T> {
    private int page = 1;
    private int size = 10;
    private String keyword = "";
    private String keywordFieldName = "name";
    private List<T> list;

    public DataPageUtilBuild(List<T> list) {
        this.list = list;
    }

    public DataPageUtilBuild<T> setPage(int page) {
        this.page = page;
        return this;
    }

    public DataPageUtilBuild<T> setSize(int size) {
        this.size = size;
        return this;
    }

    /**
     * 设置自定义过滤
     * @param cb cb
     * @return this
     */
    public DataPageUtilBuild<T> setKeyword(Predicate<? super T> cb) {
        List<T> newList = new ArrayList<>();
        this.list.forEach(x -> {
            if (cb.test(x)) {
                newList.add(x);
            }
        });
        this.list = newList;
        return this;
    }

    public Page<T> build() {
        // 先查询关键字
        int current = this.page - 1;
        List<T> collect = this.list.stream().skip((long) Math.max(current, 0) * this.size).limit(this.size).collect(Collectors.toList());
        Page<T> pageObject = new Page<>();
        pageObject.setCurrent(this.page);
        pageObject.setSize(this.size);
        pageObject.setTotal(this.list.size());
        pageObject.setRecords(collect);
        return pageObject;
    }
}
